import { Toast } from "vant";
import axios from "axios";
import {getToken} from '../utils/auth'
//全局响应拦截
const instance = axios.create({
  baseURL: "http://localhost:3000",
  timeout: 5000,
});
//请求拦截
instance.interceptors.request.use(
  function (config) {
    if(getToken()){
      config.headers.authorization= `Bearer ${getToken()}`
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    const {status} =error.response;
    console.log(status);
    if(status===401){
      Toast({type:'warning',message:'未授权 请先登录'})
      window.location.href="#/login";
    }
    return Promise.reject(error);
  }
);
//封装 get请求 

export const get = (url, params) => instance.get(url,params );
//封装 post 请求
export const post = (url, data) => instance.post(url, data);